//
//  CardData.m
//  SCRAP_ObjC
//
//  Created by Capstone Design Fall 2010 on 10/22/10.
//  Copyright 2010 Thunderwear. All rights reserved.
//

#import "CardData.h"
#import "StackAdditions.h"

@implementation CardData

@synthesize reserve, stock, waste, cascades, current, allCards, reservePoint, stockPoint, wastePoints, cascadePoints, cardHeight, cardWidth;

- (id) initGameWithSize:(CGSize)size
{	
	if ((self = [super init])) {
		current = nil;
		
		// alloc all stacks
		reserve = [[NSMutableArray alloc] initWithCapacity:13];
		waste = [[NSMutableArray alloc] init];
		cascades = [[NSMutableArray alloc] init];
		
		// create list of cards
		allCards = [[NSMutableArray alloc] init];		
		
		for (int rank=1; rank<=13; rank++) {
			for (int suit=0; suit<4; suit++) {
				char s;
				switch (suit) {
					case 0:
						s='h';
						break;
					case 1:
						s='d';
						break;
					case 2:
						s='c';
						break;
					case 3:
						s='s';
						break;
					default:
						break;
				}
				Card * card = [Card initWithRank:rank withSuit:s forIPhone:nil];
				card.isReserve = false;
				[allCards addObject:card];
			}
		}
		
		// shuffle cards
		int count = [allCards count];
		for (int i=0; i<count; ++i) {
			// Select a random element between i and end of array to swap with
			int nElements = count -i;
			int n = (arc4random() % nElements) + i;
			[allCards exchangeObjectAtIndex:i withObjectAtIndex:n];
		}
		
		// reserve
		stock = [[NSMutableArray arrayWithArray:allCards] retain];
		for (int i=0; i<13; i++) {
			Card * card = [stock pop];
			card.isReserve = true;
			card.stackRef = reserve;
			[reserve push:card];
		}
		// cascades
		for (int i=0; i<4; i++) {
			NSMutableArray * cascade = [[NSMutableArray alloc] init];
			[cascades push:cascade];			
			Card * card = [stock pop];
			card.stackRef = cascade;
			[cascade push:card];
		}		
	}
	return self;
	
}

-(BOOL) tapInWaste:(CGPoint)point {
	float x=point.x, y=point.y;
	float xRad = cardWidth/2, yRad=cardHeight/2;
	if(x>=stockPoint.x-xRad &&
	   x<=stockPoint.x+xRad &&
	   y>=stockPoint.y-yRad &&
	   y<=stockPoint.y+yRad)
	{
		return TRUE;
	}
	return FALSE;
}

-(void) dealloc {
	
	//for (Card* card in allCards)
		//[card dealloc];
	//[allCards dealloc];
	
	[reserve dealloc];
	[stock dealloc];
	[waste dealloc];
	
	//for(NSMutableArray * array in cascades)
		//[array dealloc];
	[cascades dealloc];
	
	[super dealloc];
}

@end
